package com.hupu.jrs.components.storage

import android.content.Context
import android.content.Intent
import android.webkit.CookieManager
import android.webkit.CookieSyncManager
import com.hupu.jrs.db.User
import com.hupu.jrs.service.MessageService
import com.hupu.jrs.util.SettingPrefUtil

/**
 * Created by sll on 2015/7/11.
 */

class UserStorage(private val mContext: Context) {

    var cookie: String? = null
        get() = if (isLogin) {
            user!!.cookie
        } else field
    var token: String? = null
        get() = if (!isLogin) {
            field
        } else user!!.token

    var user: User? = null
        private set

    val isLogin: Boolean
        get() = user != null && SettingPrefUtil.getLoginUid(mContext) == user!!.uid

    val uid: String
        get() = if (!isLogin) {
            ""
        } else user!!.uid!!

    fun login(user: User) {
        this.user = user
        SettingPrefUtil.setLoginUid(mContext, user.uid!!)
        val intent = Intent(mContext, MessageService::class.java)
        intent.action = MessageService.ACTION_GET
        mContext.startService(intent)
    }

    fun logout() {
        if (user!!.uid == SettingPrefUtil.getLoginUid(mContext)) {
            SettingPrefUtil.setLoginUid(mContext, "")
        }
        user = null
        this.cookie = ""
        this.token = ""
        removeCookie()
        val intent = Intent(mContext, MessageService::class.java)
        intent.action = MessageService.ACTION_CLOSE
        mContext.startService(intent)
    }

    private fun removeCookie() {
        CookieSyncManager.createInstance(mContext)
        val cookieManager = CookieManager.getInstance()
        cookieManager.removeAllCookie()
        CookieSyncManager.getInstance().sync()
    }
}
